package com.example.module_motocircle.adpater

import android.content.Context
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListUpdateCallback
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.example.module_motocircle.R
import com.example.module_motocircle.databinding.Layout1stClassCommentsItemBinding
import com.example.module_motocircle.databinding.Layout2ndClassCommentsItemBinding
import com.example.module_motocircle.databinding.LayoutCommentsFooterBinding
import com.example.module_motocircle.databinding.LayoutCommentsHeaderBinding
import com.example.module_motocircle.databinding.LayoutPostDetailsItemBinding
import com.example.module_motocircle.model.CommentRecord
import com.example.module_motocircle.model.DetailModel
import com.example.module_motocircle.model.PostItem
import com.example.module_motocircle.motocircledetail.PostDetailsViewHolder


/**
 *@author Wcj
 *@description
 *@date 2022/7/8 10:36
 */
class PostDetailsAdapter(
    private var comments: MutableList<CommentRecord> = mutableListOf(),
//    private val clickShowAll: (CommentsModel, Int) -> Unit,
//    private val onUserClick: ((String, Boolean) -> Unit)? = null,
//    private val onImageClick: ((Int, Int, List<String>, List<Info>) -> Unit)? = null,
//    //点击评论
//    private val onClickComments: ((body: PostCommentBody, replayName: String?) -> Unit)?,
//    //点击展开评论
//    private val onClickLoadMore: (() -> Boolean)? = null,
//    //失败重试
//    private val onClickRetry: (() -> Unit)? = null,
//    //长按删除
//    private val onDeleteComment: ((commentId: String) -> Unit)? = null,
//    //点赞留言
//    private val onClickLike: ((postId: String, commentId: String, onPassed: (() -> Unit)?) -> Unit)? = null,
//    private val onClickLikeView: ((postId: String, commentId: String, view: View, isLiked: Boolean, onPassed: (() -> Unit)?) -> Unit)? = null,
//    private val onFollowClick: ((post: PostModel) -> Unit)? = null,
//    //导航
//    private val onClickLocation: ((PostModel) -> Unit)? = null,
//    private val onClickMoreAfterSaleInfo: ((PostModel) -> Unit)? = null,
    private val muber:Int =2
//    , private val isOnlyTpye:Boolean =false

) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    class CommentsDiffUtil(
        private val oldData: List<CommentRecord>,
        private val newData: List<CommentRecord>
    ) : DiffUtil.Callback() {
        override fun getOldListSize(): Int {
            return oldData.size
        }

        override fun getNewListSize(): Int {
            return newData.size
        }

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldData[oldItemPosition].posts_comment_id == newData[newItemPosition].posts_comment_id
        }

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return (oldData[oldItemPosition].content == newData[newItemPosition].content &&
                    oldData[oldItemPosition].pinned == newData[newItemPosition].pinned &&
                    oldData[oldItemPosition].twoLevel == newData[newItemPosition].twoLevel &&
                    oldData[oldItemPosition].like_number == newData[newItemPosition].like_number)
        }

        override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
            return (oldData[oldItemPosition].content == newData[newItemPosition].content &&
                    oldData[oldItemPosition].pinned == newData[newItemPosition].pinned &&
                    oldData[oldItemPosition].is_like == newData[newItemPosition].is_like &&
                    oldData[oldItemPosition].like_number == newData[newItemPosition].like_number &&
                    oldData[oldItemPosition].twoLevel == newData[newItemPosition].twoLevel
                    )
        }


    }

    private var post: DetailModel? = null
    var totalCommentsSize: Int = 0
    var m1stPageCommentsSize: Int = 0
    var haveAfterSaleInfo: Int = 0


    //评论列表前原始数据偏移 帖子详情+header
    private val mCommentOffsetInData
        get() =
            muber + haveAfterSaleInfo


    //默认 帖子+header+footer
    private val mDefaultCount
        get() = 3 + haveAfterSaleInfo


    enum class Type(val value: Int) {
        POST(1), COMMENTS_HEADER(2), FIRST_COMMENTS(3), SECOND_COMMENTS(4), COMMENTS_FOOTER(5), AFTER_SALE_INFO(
            6
        )
    }

    private lateinit var mContext: Context

    private val callback = object : ListUpdateCallback {
        override fun onInserted(position: Int, count: Int) {
            this@PostDetailsAdapter.notifyItemRangeInserted(position + mCommentOffsetInData, count)
            this@PostDetailsAdapter.notifyItemChanged(
                position + mCommentOffsetInData - 1,
                count + 1
            )
        }

        override fun onRemoved(position: Int, count: Int) {
            this@PostDetailsAdapter.notifyItemRangeRemoved(position + mCommentOffsetInData, count)
        }

        override fun onMoved(fromPosition: Int, toPosition: Int) {
            this@PostDetailsAdapter.notifyItemMoved(
                fromPosition + mCommentOffsetInData,
                toPosition + mCommentOffsetInData
            )

        }

        override fun onChanged(position: Int, count: Int, payload: Any?) {
            this@PostDetailsAdapter.notifyItemRangeChanged(position + mCommentOffsetInData, count)
        }
    }

    fun setCommentsNewData(newComments: MutableList<CommentRecord>) {
        val ret = DiffUtil.calculateDiff(CommentsDiffUtil(comments, newComments), true)
        this.comments.clear()
        this.comments.addAll(newComments)
        notifyItemRangeChanged(0, mCommentOffsetInData)
        ret.dispatchUpdatesTo(callback)

    }

    override fun getItemViewType(position: Int): Int {
        return when (position) {
            0 -> Type.POST.value
            1 -> Type.COMMENTS_HEADER.value
            in 1..comments.size + 1 -> {
                return if (comments[position - mCommentOffsetInData].isFirstLevel) Type.FIRST_COMMENTS.value else Type.SECOND_COMMENTS.value
            }

            else -> Type.COMMENTS_FOOTER.value
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        mContext = parent.context
        when (viewType) {
            Type.POST.value -> {
                val binding: LayoutPostDetailsItemBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.layout_post_details_item,
                    parent,
                    false
                )
                val postDetailsViewModel =
                    PostDetailsViewHolder(binding.root)//private lateinit var mContext: Context
                binding.holder = postDetailsViewModel
                return postDetailsViewModel
            }

            Type.COMMENTS_HEADER.value -> {
                val binding: LayoutCommentsHeaderBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.layout_comments_header,
                    parent,
                    false
                )
                return CommentsHeaderViewHolder(binding.root)
            }

            Type.FIRST_COMMENTS.value -> {
                val binding: Layout1stClassCommentsItemBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.layout_1st_class_comments_item,
                    parent,
                    false
                )
                return FirstClassCommentsViewHolder(binding.root)
            }

            Type.SECOND_COMMENTS.value -> {
                val binding: Layout2ndClassCommentsItemBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.layout_2nd_class_comments_item,
                    parent,
                    false
                )
                return SecondCommentsViewHolder(
                    binding.root,
                )
            }

            else -> {
                val binding: LayoutCommentsFooterBinding = DataBindingUtil.inflate(
                    LayoutInflater.from(mContext),
                    R.layout.layout_comments_footer,
                    parent,
                    false
                )
                return CommentsFooterViewHolder(
                    binding,
                    totalCommentsSize,
                    m1stPageCommentsSize
                )
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (getItemViewType(position)) {
            Type.POST.value -> {
                val binding =
                    DataBindingUtil.getBinding<LayoutPostDetailsItemBinding>(holder.itemView)
                binding?.post = post
                post ?: return
                (holder as PostDetailsViewHolder).initView(post!!, position)
                binding?.nineGridView?.setPicsList(post?.image!!)
                binding?.nineGridView?.initView()
//                binding?.lLocation?.setOnClickListener {
//                    onClickLocation?.invoke(post!!)
//                }

//                binding?.lFollowState?.isSelected = post?.hasFollowed() ?: false
            }

            Type.COMMENTS_HEADER.value -> {
                val binding =
                    DataBindingUtil.getBinding<LayoutCommentsHeaderBinding>(holder.itemView)
                binding?.tvCommentsNum?.text = String.format("%d 条评论", totalCommentsSize)
            }

            Type.FIRST_COMMENTS.value -> {
                val binding =
                    DataBindingUtil.getBinding<Layout1stClassCommentsItemBinding>(holder.itemView)
                binding?.let {
                    val comment = comments[position - mCommentOffsetInData]
                    it.comments = comment
                    it.viewHolder = holder as FirstClassCommentsViewHolder
                    //点击评论
//                    it.root.setOnClickListener {
//                        val body = PostCommentBody().apply {
//                            this.postsId = comment.postsId
//                            this.parentId = comment.postsCommentId
//                            this.firstCommentId = comment.postsCommentId
//                            this.beReplyId = comment.createBy
//                        }
//                        onClickComments?.invoke(body, comment.requireCreateName())
//                    }
//                    if (comment.oneself == 1) {
//                        it.root.setOnLongClickListener {
//                            onDeleteComment?.invoke(comment.postsCommentId)
//                            true
//                        }
//                    }
//                    it.lLike.setOnClickListener {
//                        onClickLikeView?.invoke(
//                            comment.postsId,
//                            comment.postsCommentId,
//                            binding.ivLike,
//                            comment.isLike == 1
//                        ) {
//                            val findComment =
//                                comments.find { t -> t.postsCommentId == comment.postsCommentId }
//                                    ?: return@invoke
//                            val findPosition = comments.indexOf(findComment)
//                            handleClickLike(findComment)
//                            notifyItemChanged(findPosition + mCommentOffsetInData)
//                        }
////                        onClickLike?.invoke(comment.postsId, comment.postsCommentId) {
////                            val newPosition = comments.indexOf(comment)
////                            if (newPosition == -1) {
////                                return@invoke
////                            }
////                            val newComment = comments[newPosition]
////                            handleClickLike(newComment)
////                            notifyItemChanged(newPosition + mCommentOffsetInData)
////                        }
//                    }
                }
            }

            Type.SECOND_COMMENTS.value -> {
                val binding =
                    DataBindingUtil.getBinding<Layout2ndClassCommentsItemBinding>(holder.itemView)
                binding?.let {
                    val comment = comments[position - mCommentOffsetInData]
                    it.comments = comment
                    it.viewHolder = holder as SecondCommentsViewHolder
//                    it.root.setOnClickListener {
//                        val body = PostCommentBody().apply {
//                            this.postsId = comment.postsId
//                            this.parentId = comment.postsCommentId
//                            this.firstCommentId = comment.firstCommentId
//                            this.beReplyId = comment.createBy
//                        }
//                        onClickComments?.invoke(body, comment.requireCreateName())
//                    }
                    //圆角处理
//                    if (comments[position - mCommentOffsetInData].topRound) it.l2ndComments.setBackgroundResource(
//                        R.drawable.shape_bg_mask_round_top_4dp
//                    )
//                    if (comments[position - mCommentOffsetInData].bottomRound) it.l2ndComments.setBackgroundResource(
//                        R.drawable.shape_bg_mask_round_bottom_4dp
//                    )
//                    if (comments[position - mCommentOffsetInData].rect) it.l2ndComments.setBackgroundResource(
//                        R.drawable.shape_bg_mask_rect
//                    )
//                    if (comment.oneself == 1) {
//                        it.root.setOnLongClickListener {
//                            onDeleteComment?.invoke(comment.postsCommentId)
//                            true
//                        }
//                    }
//                    it.lLike.setOnClickListener {
//
//                        onClickLikeView?.invoke(
//                            comment.postsId,
//                            comment.postsCommentId,
//                            binding.ivLike,
//                            comment.isLike == 1
//                        ) {
//                            val findComment =
//                                comments.find { t -> t.postsCommentId == comment.postsCommentId }
//                                    ?: return@invoke
//                            val findPosition = comments.indexOf(findComment)
//                            handleClickLike(findComment)
//                            notifyItemChanged(findPosition + mCommentOffsetInData)
//                        }
////                        onClickLike?.invoke(comment.postsId, comment.postsCommentId) {
////                            val newPosition = comments.indexOf(comment)
////                            if (newPosition == -1) {
////                                return@invoke
////                            }
////                            val newComment = comments[newPosition]
////                            handleClickLike(newComment)
////                            notifyItemChanged(newPosition + mCommentOffsetInData)
////                        }
//                    }
                }
            }

            Type.COMMENTS_FOOTER.value -> {
                val binding =
                    DataBindingUtil.getBinding<LayoutCommentsFooterBinding>(holder.itemView)
                //重新设置评论数据
                (holder as CommentsFooterViewHolder).setCommentsSize(
                    totalCommentsSize,
                    m1stPageCommentsSize
                )
                binding?.viewHolder = holder
                //footer状态切换
//                noMore = holder::noMore
//                loading = holder::loading
//                error = holder::error
            }
        }

    }


//    private fun handleClickLike(comment: PostCommentsModel) {
//        if (comment.isLike == 1) {
//            comment.isLike = 0
//            if (comment.likeNumber > 0)
//                comment.likeNumber--
//        } else {
//            comment.isLike = 1
//            comment.likeNumber++
//        }
//    }


    override fun getItemCount(): Int {
        return comments.size + mDefaultCount
    }


    fun setPostInfo(post: DetailModel?, totalSize: Int, _1stSize: Int) {
        this.post = post
        this.totalCommentsSize = totalSize
        this.m1stPageCommentsSize = _1stSize
        notifyItemRangeChanged(0, mCommentOffsetInData)
        notifyItemChanged(itemCount)
    }

//    fun setAfterSaleInfo(list: List<AfterSalePageItem>?, isOnlyTpye: Boolean = false) {
//        this.afterSaleInfo = list
//        haveAfterSaleInfo = if (!list.isNullOrEmpty() && post?.inAfterSaleStatus() == true) 1 else 0
//        notifyItemRangeChanged(0, mCommentOffsetInData)
//        notifyItemChanged(itemCount)
//    }


    //无更多数据
    var noMore: (() -> Unit)? = null

    //加载中
    var loading: (() -> Unit)? = null

    //加载错误
    var error: (() -> Unit)? = null

}
class CommentsHeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

class AfterSaleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

class CannotCommentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class CommentsFooterViewHolder(
    val binding: LayoutCommentsFooterBinding,
//    private val onClickLoadMore: (() -> Boolean)? = null,
//    private val onClickRetry: (() -> Unit)? = null,
    private var totalCommentSize: Int,
    private var m1stPageCommentsSize: Int
) :
    RecyclerView.ViewHolder(binding.root) {

    fun setCommentsSize(total: Int, m1stPageSize: Int) {
        this.totalCommentSize = total
        this.m1stPageCommentsSize = m1stPageSize
    }

    //是否显示
    fun show(): Boolean {
        val size = totalCommentSize - m1stPageCommentsSize
        return size > 0 && totalCommentSize > 10 && m1stPageCommentsSize >= 10
    }

    //format剩余评论数据
    fun formatRemainingCommentsNum(): String {
        val size = totalCommentSize - m1stPageCommentsSize
        return String.format("展开%d评论", size)
    }

    //点击加载更多
//    fun loadMore() {
//        if (onClickLoadMore?.invoke() != true)
//            return
//    }

//    private fun retry(view: View) {
//        onClickRetry?.invoke()
//    }

//    fun noMore() {
//        binding.lLoad.visibility = View.VISIBLE
//        binding.lLoadStatus.loadMoreLoadingView.visibility = View.GONE
//        binding.lLoadStatus.loadMoreLoadEndView.visibility = View.VISIBLE
//        binding.lLoadStatus.loadMoreLoadFailView.visibility = View.GONE
//        binding.tv.visibility = View.GONE
//    }
//
//    fun loading() {
//        binding.lLoad.visibility = View.VISIBLE
//        binding.lLoadStatus.loadMoreLoadingView.visibility = View.VISIBLE
//        binding.lLoadStatus.loadMoreLoadEndView.visibility = View.GONE
//        binding.lLoadStatus.loadMoreLoadFailView.visibility = View.GONE
//        binding.tv.visibility = View.GONE
//    }
//
//    fun error() {
//        binding.lLoad.visibility = View.VISIBLE
//        binding.lLoadStatus.loadMoreLoadingView.visibility = View.GONE
//        binding.lLoadStatus.loadMoreLoadEndView.visibility = View.GONE
//        binding.lLoadStatus.loadMoreLoadFailView.visibility = View.VISIBLE
//        binding.tv.visibility = View.GONE
//        binding.lLoadStatus.loadMoreLoadFailView.setOnClickListener(::retry)
//    }

}

class SecondClassRouteCommentsViewHolder(
    itemView: View,
//    private val clickShowAll: (CommentsModel, Int) -> Unit,
//    val onUserClick: ((String, Boolean) -> Unit)? = null
) :
    RecyclerView.ViewHolder(itemView) {
    val mBinding: Layout2ndClassCommentsItemBinding by lazy {
        DataBindingUtil.getBinding(itemView)!!
    }

//    fun clickAllComments(comments: CommentsModel) {
//        clickShowAll.invoke(comments, this.absoluteAdapterPosition - 2)
//    }

    //格式化回复评论内容 XXX回复：YY
    fun formatReplayContent(content: String, replyName: String?): CharSequence {
        val prefix = String.format("%s", replyName ?: "未知用户")
        val formatContent = String.format("回复%s：%s", prefix, content)
        val start = formatContent.indexOf(prefix)
        val end = start + prefix.length
        val spannableStringBuilder = SpannableStringBuilder(formatContent)
        spannableStringBuilder.setSpan(
            ForegroundColorSpan(ContextCompat.getColor(itemView.context, com.example.lib_common.R.color.color_919191)),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        return spannableStringBuilder
    }

    fun clickUser() {
        if (mBinding.comments?.isOfficial() == true)
            return
//        onUserClick?.invoke(mBinding.comments!!.createBy, false)
    }


}


class SecondCommentsViewHolder(
    itemView: View,
//    val haveAfterSaleInfo: Boolean = false,
//    private val clickShowAll: (CommentsModel, Int) -> Unit,
//    val onUserClick: ((String, Boolean) -> Unit)? = null
) :
    RecyclerView.ViewHolder(itemView) {
    val mBinding: Layout2ndClassCommentsItemBinding by lazy {
        DataBindingUtil.getBinding(itemView)!!
    }

//    fun clickAllComments(comments: CommentsModel) {
//        clickShowAll.invoke(comments, this.absoluteAdapterPosition - if (haveAfterSaleInfo) 3 else 2)
//    }

    //格式化回复评论内容 XXX回复：YY
    fun formatReplayContent(content: String, replyName: String?): CharSequence {
        val prefix = String.format("%s", replyName ?: "未知用户")
        val formatContent = String.format("回复%s：%s", prefix, content)
        val start = formatContent.indexOf(prefix)
        val end = start + prefix.length
        val spannableStringBuilder = SpannableStringBuilder(formatContent)
        spannableStringBuilder.setSpan(
            ForegroundColorSpan(ContextCompat.getColor(itemView.context, com.example.lib_common.R.color.color_919191)),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        return spannableStringBuilder
    }

    fun clickUser() {
        if (mBinding.comments?.isOfficial() == true)
            return
//        onUserClick?.invoke(mBinding.comments!!.createBy, false)
    }


}

class FirstClassCommentsViewHolder(itemView: View, val onUserClick: ((String, Boolean) -> Unit)? = null) : RecyclerView.ViewHolder(itemView) {
    val mBinding: Layout1stClassCommentsItemBinding by lazy {
        DataBindingUtil.getBinding(itemView)!!
    }

    fun clickUser() {
        if (mBinding.comments?.isOfficial() == true)
            return
//        onUserClick?.invoke(mBinding.comments!!.createBy, false)
    }
}

class FirstClassRouteCommentsViewHolder(itemView: View, val onUserClick: ((String, Boolean) -> Unit)? = null) : RecyclerView.ViewHolder(itemView) {
    val mBinding: Layout1stClassCommentsItemBinding by lazy {
        DataBindingUtil.getBinding(itemView)!!
    }

//    fun clickUser() {
//        if (mBinding.comments?.isOfficial() == true)
//            return
//        onUserClick?.invoke(mBinding.comments!!.createBy, false)
//    }
}


abstract class EndlessRecyclerOnScrollListener : RecyclerView.OnScrollListener() {
    //用来标记是否正在向上滑动
    private var isSlidingUpward = false
    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        val manager = recyclerView.layoutManager as LinearLayoutManager?
        // 当不滑动时
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            //获取最后一个完全显示的itemPosition
            val lastItemPosition = manager!!.findLastCompletelyVisibleItemPosition()
            val itemCount = manager.itemCount

            // 判断是否滑动到了最后一个item，并且是向上滑动
            if (lastItemPosition == itemCount - 1 && isSlidingUpward) {
                //加载更多
                onLoadMore()
            }
        }
    }

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        // 大于0表示正在向上滑动，小于等于0表示停止或向下滑动
        isSlidingUpward = dy > 0
    }

    /**
     * 加载更多回调
     */
    abstract fun onLoadMore()
}
